package com.loongtech.bi.action;

import com.loongtech.bi.entity.system.EntitySystemLog;
import com.loongtech.bi.entity.system.UrlClass;
import com.loongtech.bi.manager.system.SysFunctionManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysUserProjectRoleManager;
import com.loongtech.bi.support.Session;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 前端拉取数据总Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("session")
@RequestMapping("/data")
public class DataBiAction extends  TransferHelper {
	private static final long serialVersionUID = 1L;
	@Autowired
	private Session session;

    @Autowired
    private SysUserProjectRoleManager sysUserProjectRoleManager;
    @Resource
    private SysLogManager sysLogManager;
    @Resource
    private SysFunctionManager sysFunctionManager;

    public static final Map<String, String> RESULT_DATA_ALIVE_30SEC = new ConcurrentHashMap<>();
    public static final Map<String, String> RESULT_DATA_ALIVE_30MIN = new ConcurrentHashMap<>();
    public static final Map<String, String> RESULT_DATA_ALIVE_3HOUR = new ConcurrentHashMap<>();

    @RequestMapping(value = "get.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void get(HttpServletRequest request, HttpServletResponse response, @RequestParam String p, @RequestParam String f, @RequestParam String a, @RequestParam String ps, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            UrlClass url = sysUserProjectRoleManager.getUrl(session.getUserId(), Integer.parseInt(p), Integer.parseInt(f));
            if (url == null) {
                result.put("res", "2");
                printToJson(response, result, callback);
            } else {
                //保存请求信息
                EntitySystemLog entitySystemLog = new EntitySystemLog();
                entitySystemLog.setOperator(session.getUserName());
                entitySystemLog.setOperTime(Time.currentDate());
                entitySystemLog.setGameId(p);
                entitySystemLog.setAction(f);
                sysLogManager.persist(entitySystemLog);

                if (StringUtils.isNotEmpty(ps) && (ps.contains("&uid=") || ps.startsWith("uid="))) {
                    String[] pss = ps.split("uid=");
                    String pre = pss[0];
                    String mid = "uid=" + session.getUserName();
                    String end = pss.length > 1 ? (pss[1].contains("&") ? pss[1].substring(pss[1].indexOf("&"), pss[1].length() - 1) : "") : "";
                    ps = pre + mid + end;
                }

                String uri = url.getURL() + "/" + a + ".do?" + ps;
                String data = null;

                String key = Utils.md5(uri);
                String username = session.getUserName();
                int random = new Random().nextInt();

                boolean isAdmin = "admin".equals(username);

               /* if (isAdmin) {
                    System.out.println();
                    System.out.println(key + " " + Time.getNowDateDetailStr() + " " + random);
                }*/

                if (uri.contains("/realTime/") || uri.contains("/market/")) {
                    if (uri.contains("/market/") && StringUtils.isNotEmpty(url.getName()) && !url.getName().contains("实时")) {
                        data = RESULT_DATA_ALIVE_3HOUR.get(key);
                    } else {
                        data = RESULT_DATA_ALIVE_30SEC.get(key);
                    }
                } else if (!uri.contains("/flow/")) {
                    data = RESULT_DATA_ALIVE_30MIN.get(key);
                }

                if (data == null) {
                   /* if (isAdmin) {
                        System.out.println("=====================  (" + username + ")拉取URL: " + uri);
                    }*/

                    data = Utils.httpGet(uri, null);

                    if (StringUtils.isNotEmpty(data) && data.contains("完美世界") && data.contains("用户名")) {  // 404
                        result.put("res", "2");
                        printToJson(response, result, callback);

                       /* if (isAdmin) {
                            System.out.println("--------------------  (" + username + ")没拉到！");
                        }*/

                        return;
                    } else {
                        if (uri.contains("/realTime/") || uri.contains("/market/")) {
                            if (uri.contains("/market/") && StringUtils.isNotEmpty(url.getName()) && !url.getName().contains("实时")) {
                                RESULT_DATA_ALIVE_3HOUR.put(key, data);
                            } else {
                                RESULT_DATA_ALIVE_30SEC.put(key, data);
                            }
                        } else if (!uri.contains("/flow/")) {
                            RESULT_DATA_ALIVE_30MIN.put(key, data);
                        }
                    }
                } else {
                    /*if (isAdmin) {
                        if (uri.contains("/realTime/") || uri.contains("/market/")) {
                            if (uri.contains("/market/") && StringUtils.isNotEmpty(url.getName()) && !url.getName().contains("实时")) {
                                System.out.println("=====================  (" + username + ")命中3小时：" + uri);
                            } else {
                                System.out.println("=====================  (" + username + ")命中30秒：" + uri);
                            }
                        } else if (!uri.contains("/flow/")) {
                            System.out.println("=====================  (" + username + ")命中30分钟：" + uri);
                        }
                    }*/
                }

                printToJson(response, data, callback);

                /*if (isAdmin) {
                    System.out.println(key + " " + Time.getNowDateDetailStr() + " " + random);
                    System.out.println();
                }*/
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
	}

    @RequestMapping(value = "clear.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void clear(HttpServletRequest request, HttpServletResponse response, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            RESULT_DATA_ALIVE_30SEC.clear();
            RESULT_DATA_ALIVE_30MIN.clear();
            RESULT_DATA_ALIVE_3HOUR.clear();

            result.put("res", "0");
            result.put("msg", "缓存清理成功！");
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }
}
